package org.study.memcached.boot.config;

import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.study.memcached.boot.util.MemcachedUtils;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2024年01月11日
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(value = {MemcachedProperties.class})
public class MemcachedConfig {
    @Bean
    public MemcachedClient memcachedClient(MemcachedProperties memcachedProperties) {
        InetSocketAddress address = new InetSocketAddress(memcachedProperties.getHost(), memcachedProperties.getPort());
        // 创建MemcachedClient对象
        MemcachedClient memcachedClient = null;
        try {
            memcachedClient = new MemcachedClient(address);
            // 手动给工具类注入依赖
            MemcachedUtils.setMemcachedClient(memcachedClient);
        } catch (IOException ex) {
            log.error("创建MemcachedClient异常", ex);
            throw new RuntimeException(ex);
        }
        return memcachedClient;
    }
}
